//
//  KATTableHeader.m
//  KATFramework
//
//  Created by Kantice on 16/7/14.
//  Copyright © 2016年 KatApp. All rights reserved.
//

#import "KATTableHeader.h"

@implementation KATTableHeader

#pragma -mark 类方法

//获取实例
+ (instancetype)tableHeader
{
    return [[[KATTableHeader alloc] init] autorelease];
}


#pragma -mark 对象方法

//初始化数据
- (void)initWithHeight:(float)height andScrollView:(UIScrollView *)scrollView
{
    if(scrollView)
    {
        if(height<=0)
        {
            height=scrollView.bounds.size.width*0.2;
        }
        
        self.scrollView=scrollView;
        self.frame=CGRectMake(0, -height, scrollView.bounds.size.width, height);
        self.dragHeight=height*1.75;
        self.state=THEADER_STATE_READY;
        self.isReleaseToLoad=NO;
        self.animationFinishDuration=0.8;
        self.eventDelegate=nil;
        self.locked=NO;
        self.ignoreConflicts=YES;
        
        [self.scrollView addSubview:self];
        
        //监听
        [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        
        _headerQueue=dispatch_queue_create("kat_table_header_queue", DISPATCH_QUEUE_SERIAL);
    }
}


//下拉
- (void)pull
{
    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(headerPullWithProgress:)])
    {
        float progress=(-_scrollView.contentOffset.y)/_dragHeight;
        
        if(progress<0)
        {
            progress=0;
        }
        
        if(progress>1.0)
        {
            progress=1.0;
        }
        
        [_stateDelegate headerPullWithProgress:progress];
    }
    
    _state=THEADER_STATE_PULLING;
}


//直接加载
- (void)load
{
    if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(tableHeaderDidStartLoad:)])
    {
        [_eventDelegate tableHeaderDidStartLoad:self];
    }
}


//开始加载
- (void)startLoad
{
    if(!_ignoreConflicts)//检测冲突
    {
        if(self.scrollView.contentInset.bottom>0)//正在加载中
        {
            return;
        }
    }
    
    _state=THEADER_STATE_LOADING;
    
    dispatch_async(_headerQueue, ^
    {
        dispatch_sync(dispatch_get_main_queue(), ^
        {
            if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(headerStartLoad)])
            {
                [_stateDelegate headerStartLoad];
            }
        });
       
        [NSThread sleepForTimeInterval:0.8];//防止冲突，先挂起一会
       
        dispatch_sync(dispatch_get_main_queue(), ^
        {
            if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(tableHeaderDidStartLoad:)])
            {
                [_eventDelegate tableHeaderDidStartLoad:self];
            }
        });
    });
}


//完成加载
- (void)finishLoad
{
    _state=THEADER_STATE_FINISH;
    _scrollView.userInteractionEnabled=NO;
    
    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(headerFinishLoad)])
    {
        [_stateDelegate headerFinishLoad];
    }
    
    [UIView animateWithDuration:_animationFinishDuration animations:^
    {
        self.scrollView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
    }
    completion:^(BOOL finished)
    {
        _state=THEADER_STATE_READY;
        _scrollView.userInteractionEnabled=YES;
        
        if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(headerRestoreAfterLoad)])
        {
            [_stateDelegate headerRestoreAfterLoad];
        }
    }];
}


//监听状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if(_scrollView)
    {
        if(_scrollView.contentOffset.y<0)
        {
            if(_scrollView.contentOffset.y<=-_dragHeight)//下拉完成
            {
                if(_state==THEADER_STATE_PULLING)
                {
                    if(_stateDelegate && [_stateDelegate respondsToSelector:@selector(headerFinishPull)])
                    {
                        [_stateDelegate headerFinishPull];
                    }
                    
                    _state=THEADER_STATE_RELEASE;
                }
                
                if(_state==THEADER_STATE_RELEASE)//下拉完成状态
                {
                    if(_isReleaseToLoad)//需要松开后
                    {
                        if(_scrollView.decelerating)//减速中(松开后)
                        {
                            if(!_locked)
                            {
                                [self startLoad];
                            }
                        }
                    }
                    else//不需要松开，直接加载
                    {
                        if(!_locked)
                        {
                            [self startLoad];
                        }
                    }
                }
            }
            else
            {
                if(_state==THEADER_STATE_LOADING)
                {
                    if(_scrollView.decelerating)
                    {
                        if(self.scrollView.contentInset.top<=0)
                        {
                            [UIView animateWithDuration:0.1 animations:^
                            {
                                self.scrollView.contentInset=UIEdgeInsetsMake(self.bounds.size.height, 0, 0, 0);
                            }
                            completion:^(BOOL finished)
                            {
                                ;
                            }];
                        }
                    }
                }
                else if(_state==THEADER_STATE_FINISH)
                {
                    
                }
                else
                {
                    [self pull];
                }
            }
        }
        else
        {
            if(_state!=THEADER_STATE_LOADING && _state!=THEADER_STATE_FINISH)
            {
                _state=THEADER_STATE_READY;
            }
        }
    }
}


//释放内存
- (void)dealloc
{
    if(_scrollView)
    {
        @try
        {
            [_scrollView removeObserver:self forKeyPath:@"contentOffset"];//移除监听
        }
        @catch(NSException *exception)
        {
            NSLog(@"<Exception> %@ : %@",self,exception);
        }
    }
    
    if(_headerQueue)
    {
        dispatch_release(_headerQueue);
    }
    
    [super dealloc];
}

@end
